# -*- coding: utf-8 -*-
import telnetlib,time,sqlite3,MySQLdb,pingthread
from threading import Thread
from Queue import Queue
from time import sleep,time

timeout=2
count = 1
psize = 64
dest_addr="172.16.100.31"
# 单个ping测试
# ping.verbose_ping(dest_addr)
# print ping.quiet_ping(dest_addr,timeout,count,psize)


# 从mysql的rnd表取ndip数据
conn=MySQLdb.connect(host="172.16.100.31",user="root",passwd="admin",db="rainbow_3_0")
cursor=conn.cursor()
# cursor.execute("select dscfgnwipaddr from rnd order by dscfgnwipaddr desc limit 10")
cursor.execute("select dscfgnwipaddr from rnd order by dscfgnwipaddr")
nds=cursor.fetchall()
cursor.close()
conn.close()
print len(nds)

#q是任务队列
#NUM是并发线程总数
#JOBS是有多少任务
q = Queue()
NUM = 25
l=[]
#具体的处理函数，负责处理单个任务
def do_somthing_using(arguments):
	n={}
	n["ndip"]=arguments[0]
	n["bAlive"]="0"
	bAlive=pingthread.do_one(arguments[0],timeout,psize)
	# print bAlive
	if bAlive==None:
		l.append(n)

	
#这个是工作进程，负责不断从队列取数据并处理
def working():
	while True:
		arguments = q.get()
		do_somthing_using(arguments)
		q.task_done()
start=time()
#fork NUM个线程等待队列
for i in range(NUM):
	t = Thread(target=working)
	t.setDaemon(True)
	t.start()
#把JOBS排入队列
for i in nds:
	q.put(i)
#等待所有JOBS完成
q.join()
print time()-start
print "all jobs have done"
# print l
print "ready to saving data..."	
	
# 保存到sqlite
conn=sqlite3.connect(r'lkt.db3')
conn.text_factory = str
conn.execute("update rnd set bExist=0")

print len(l)
for x in l:
	print x
	ndip=conn.execute("select ndip from rnd where ndip='"+x["ndip"]+"'").fetchone()
	if ndip:
		sql="update rnd set bAlive="+x["bAlive"]+",bExist=1 where ndip='"+x["ndip"]+"'"
	else:
		sql="insert into rnd(ndip,snmp0,snmp1,bAlive) values('"+x["ndip"]+"','','',"+x["bAlive"]+")"
	# print sql
	conn.execute(sql)
print "commit data to sqlite"
conn.commit()
conn.close()

